package com.lancoo.edu.platform.operation.commons.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.lancoo.edu.platform.operation.backupRestore.constant.DataBaseTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;

/**
 * @author zhang.ws
 * @date 2024/3/25 10:28
 * @description 数据源配置
 */
@Configuration
@Slf4j
public class DatabaseSourceConfig {

    @Resource
    private LancooConfig lancooConfig;

    /**
     * 数据库连接地址
     */
    @Value("${spring.datasource.url}")
    private String url;


    /**
     * 获取数据源
     *
     * @return 返回数据源
     */
    @Bean
    public DataSource getDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        log.info("【项目数据库：{}】", lancooConfig.getDatabaseType());
        // 当为达梦数据库时，替换
        if (Objects.equals(lancooConfig.getDatabaseType(), DataBaseTypeEnum.DM.getDatabaseType())) {
            url = url.replace(DataBaseTypeEnum.MYSQL_WINDOWS.getDatabaseType(), DataBaseTypeEnum.DM.getDatabaseType());
        }
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(lancooConfig.getUserName());
        druidDataSource.setPassword(lancooConfig.getPassword());
        return druidDataSource;
    }


}
